package com.qiniuyun.threedgenerator.config;

import com.qiniuyun.threedgenerator.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Map;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理文件大小超限异常
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<?> handleMaxSizeException(MaxUploadSizeExceededException e) {
        logger.warn("文件大小超过限制: {}", e.getMessage());
        return ResponseUtil.error("文件大小超过限制", HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理404异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<?> handleNotFoundException(NoHandlerFoundException e) {
        logger.warn("接口不存在: {}", e.getRequestURL());
        return ResponseUtil.error("接口不存在", HttpStatus.NOT_FOUND);
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleGlobalException(Exception e) {
        logger.error("系统错误: ", e);
        return ResponseUtil.error("系统错误: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}